<?php

//安全码验证&&版本验证
function validate($data)
{
    $data = $data;
    $safecode = C('safecode');
    $apiversion = C('apiversion');
    if ($safecode == $data['safecode'] && $apiversion == $data['apiversion']) {
        $ReData['code'] = '200';
        $ReData['msg'] = '验证成功!';
        $ReData['data'] = $data;
    } else {
        $ReData['code'] = '-200';
        $ReData['msg'] = '验证失败!';
        $ReData['data'] = $data;
    }
    return $ReData;
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function client_ip($type = 0, $adv = true)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos)
                unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * @desc 获取当前的token值
 * @author Earl <guo@seosite.cn> .
 * @updateTime
 * @param null $type
 * @return mixed|string
 */
function _get_token($type = null)
{
    $token = !empty($type)?$_POST[$type]:I('post.token');

    if (empty($token)) return '';

    $user_info = (array)\Org\Util\JWT::decode($token, C('safecode'), array('HS256'));

    $map['uid'] = $user_info['id'];
    $map['user_token']  = $token;
    $map['platform']    = 'wap';
    $ret = M('token')->where($map)->find();

    if (empty($ret) || ($ret['expire_time'] < NOW_TIME && $ret['expire_time'] !=0)) $token = '';
    return $token;
}

/**
 * @desc 设置token
 * @author Earl <guo@seosite.cn> .
 * @updateTime
 * @param $data
 * @return string
 */
function _set_token($data,$is_admin,$expire_time)
{
    $token = '';
    if (!empty($data)) {
        $token = \Org\Util\JWT::encode($data, C('safecode'));
    }

    $token_map['uid']       = $data['id'];
    $token_map['platform']  = 'wap';
    $token_map['is_admin']  = $is_admin;

    $token_exist = M('token')->where($token_map)->find();
    $t = NOW_TIME + $expire_time;
    $expire_time = empty($expire_time) ? 0 : $t;
    if ($token_exist) {
        $save_data = [
            'user_token' => $token,
            'expire_time' => $expire_time
        ];
        M('token')->where(array('id' => $token_exist['id']))->save($save_data);
    } else {
        //添加token至token表中
        $add_data = array(
            'uid'           =>  $data['id'],
            'user_token'    =>  $token,
            'expire_time'   =>  $expire_time,
            'platform'      =>  'wap',
            'is_admin'      =>  $is_admin,
        );
        $ret = M('token')->add($add_data);
    }

    return $token;
}

/**
 * @desc 清空用户token
 * @author Earl <guo@seosite.cn> .
 * @updateTime
 * @param $token
 * @return bool
 */
function _unset_token($token)
{
    $is_exist = M('token')->where(array('user_token' => $token))->find();
    if ($is_exist){
        M('token')->where(array('user_token' => $token))->delete();
    }
    return true;
}
/**
 * @desc 解码token，返回原$data内容
 * @author Earl <guo@seosite.cn> .
 * @updateTime
 * @param $token
 * @return array
 */
function decode_token($token = '')
{
    $token = empty($token)?_get_token():$token;

    if (empty($token)) return '';

    $info = (array)\Org\Util\JWT::decode($token, C('safecode'), array('HS256'));
    $info['phone'] = substr_replace($info['phone'],'****',3,4);
    $info['password'] = '+++++++财经直播++++++++';

    list($info['rank'],$info['rank_text']) = userRank($info['id']);
    return $info;
}

/**
 * @desc 返回rank等级
 * @author Egor<http://gitee.com/seosite>
 * @param $uid
 * @return array
 */
function userRank($uid)
{
    $level = M('user')->where(array('id'=>$uid))->getField('level');
    if($level<30){
        $rank = 1;
    }else if($level<70){
        $rank = 2;
    }else if($level<190){
        $rank = 3;
    }else if($level<385){
        $rank = 4;
    }else if($level<640){
        $rank = 5;
    }else if($level<1040){
        $rank = 6;
    }else if($level<1665){
        $rank = 7;
    }else if($level<2715){
        $rank = 8;
    }else if($level<4290){
        $rank = 9;
    }else if($level<6690){
        $rank = 10;
    }else if($level<9840){
        $rank = 11;
    }else if($level<14840){
        $rank = 12;
    }else if($level<20840){
        $rank = 13;
    }else if($level<27340){
        $rank = 14;
    }else if($level<34500){
        $rank = 15;
    }else if($level<42700){
        $rank = 16;
    }else if($level<52580){
        $rank = 17;
    }else if($level<65400){
        $rank = 18;
    }else if($level<83400){
        $rank = 19;
    }else if($level<110000){
        $rank = 20;
    }else if($level<140000){
        $rank = 21;
    }else if($level<175000){
        $rank = 22;
    }else if($level<215000){
        $rank = 23;
    }else if($level<268000){
        $rank = 24;
    }else if($level<345000){
        $rank = 25;
    }else if($level<454000){
        $rank = 26;
    }else if($level<588000){
        $rank = 27;
    }else if($level<760000){
        $rank = 28;
    }else if($level<1000000){
        $rank = 29;
    }else{
        $rank = 30;
    }

//    M('User')->where(['id'=>$uid])->setField('rank',$rank);

    return array($rank,'VIP'.$rank);
}

/**
 * @desc 返回用户昵称和头像
 * @author Earl <guo@seosite.cn> .
 * @updateTime
 * @param $uid
 * @return array|string
 */
function getUserNameAndHeadByID($uid)
{
    $info = M('user')->field('nickname')->find($uid);
    if (empty($info)) return "";
    return array($info['nickname'], $info['headimgurl']);
}

/**
 * PHP DES 加密程式
 *
 * @param $key 密鑰（必须要八个字符）
 * @param $encrypt 要加密的明文
 * @return string 密文
 */
function do_encrypt ($encrypt)
{
    // 根據 PKCS#7 RFC 5652 Cryptographic Message Syntax (CMS) 修正 Message 加入 Padding
    $block = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_ECB);
    $pad = $block - (strlen($encrypt) % $block);
    $encrypt .= str_repeat(chr($pad), $pad);

    // 不需要設定 IV 進行加密
    $passcrypt = mcrypt_encrypt(MCRYPT_DES, C('DES_KEY'), $encrypt, MCRYPT_MODE_ECB);
    return base64_encode($passcrypt);
}

/**
 * PHP DES 解密程式
 *
 * @param $key 密鑰（必须要八个字符）
 * @param $decrypt 要解密的密文
 * @return string 明文
 */
function do_decrypt ( $decrypt)
{
    // 不需要設定 IV
    $str = mcrypt_decrypt(MCRYPT_DES, C('DES_KEY'), base64_decode($decrypt), MCRYPT_MODE_ECB);

    // 根據 PKCS#7 RFC 5652 Cryptographic Message Syntax (CMS) 修正 Message 移除 Padding
    $pad = ord($str[strlen($str) - 1]);
    return substr($str, 0, strlen($str) - $pad);
}

/** 返回首字母
 * @desc
 * @author Egor<http://gitee.com/seosite>
 * @param $str
 * @return string
 */
function get_first_char( $str )
{
    $fchar = $str[0];
    if ( ord( "A" ) <= ord( $fchar ) && ord( $fchar ) <= ord( "z" ) )
    {
        return strtoupper( $fchar );
    }
    $str = iconv( "UTF-8", "gb2312", $str );
    $asc = ord( $str[0] ) * 256 + ord( $str[1] ) - 65536;
    if ( -20319 <= $asc && $asc <= -20284 )
    {
        return "A";
    }
    if ( -20283 <= $asc && $asc <= -19776 )
    {
        return "B";
    }
    if ( -19775 <= $asc && $asc <= -19219 )
    {
        return "C";
    }
    if ( -19218 <= $asc && $asc <= -18711 )
    {
        return "D";
    }
    if ( -18710 <= $asc && $asc <= -18527 )
    {
        return "E";
    }
    if ( -18526 <= $asc && $asc <= -18240 )
    {
        return "F";
    }
    if ( -18239 <= $asc && $asc <= -17923 )
    {
        return "G";
    }
    if ( -17922 <= $asc && $asc <= -17418 )
    {
        return "H";
    }
    if ( -17417 <= $asc && $asc <= -16475 )
    {
        return "I";
    }
    if ( -16474 <= $asc && $asc <= -16213 )
    {
        return "J";
    }
    if ( -16212 <= $asc && $asc <= -15641 )
    {
        return "K";
    }
    if ( -15640 <= $asc && $asc <= -15166 )
    {
        return "L";
    }
    if ( -15165 <= $asc && $asc <= -14923 )
    {
        return "M";
    }
    if ( -14922 <= $asc && $asc <= -14915 )
    {
        return "N";
    }
    if ( -14914 <= $asc && $asc <= -14631 )
    {
        return "P";
    }
    if ( -14630 <= $asc && $asc <= -14150 )
    {
        return "Q";
    }
    if ( -14149 <= $asc && $asc <= -14091 )
    {
        return "R";
    }
    if ( -14090 <= $asc && $asc <= -13319 )
    {
        return "S";
    }
    if ( -13318 <= $asc && $asc <= -12839 )
    {
        return "T";
    }
    if ( -12838 <= $asc && $asc <= -12557 )
    {
        return "W";
    }
    if ( -12556 <= $asc && $asc <= -11848 )
    {
        return "X";
    }
    if ( -11847 <= $asc && $asc <= -11056 )
    {
        return "Y";
    }
    if ( -11055 <= $asc && $asc <= -10247 )
    {
        return "Z";
    }
}
?>